﻿function RoleMgmt() {
    this.SearchGrid = null;
    this.NameBox = null;
    this.DescriptionBox = null;
    this.DisableCheck = null;
    this.PrivilegeTree = null;
    this.RoleTabsStrip = null;
    this.RoleID = null;

    this.GetActiveTabIndex = function () {
        if (this.RoleTabsStrip != null) {
            return this.RoleTabsStrip.get_selectedTab().get_index();
        }
        else {
            throw 'Cannot load RadTabStrip.';
        }
    }

    this.SelectTabByName = function (pName) {
        if (this.RoleTabsStrip != null) {
            return this.RoleTabsStrip.findTabByText(pName).set_selected(true);
        }
        else {
            throw 'Cannot load Role Tabs.';
        }
    }

    this.ClearAllDetails = function () {
        var hasError = false;
        var exceptionDetails = '';

        if (this.NameBox == null) {
            hasError = true;
            exceptionDetails += 'Cannot load Name.';
        }

        if (this.DescriptionBox == null) {
            hasError = true;
            exceptionDetails += 'Cannot load Description.';
        }

        if (this.DisableCheck == null) {
            hasError = true;
            exceptionDetails += 'Cannot load Disable.';
        }

        if (this.PrivilegeTree == null) {
            hasError = true;
            exceptionDetails += 'Cannot load Privelages.';
        }

        if (this.RoleID == null) {
            hasError = true;
            exceptionDetails += 'Cannot load RoleID.';
        }

        if (!hasError) {
            this.NameBox.set_value('');
            this.DescriptionBox.set_value('');
            this.DisableCheck.checked = false;
            this.PrivilegeTree.uncheckAllNodes();
            this.RoleID.value = '';
        }
        else {
            throw exceptionDetails;
        }
    }

    this.PerformNewOperation = function () {
        var hasError = false;
        var exceptionDetails = '';

        if (this.RoleTabsStrip == null) {
            hasError = true;
            exceptionDetails += 'Cannot load role tabs.';
        }

        try {
            this.ClearAllDetails();
            this.SelectTabByName('Role Details');
        }
        catch (ex) {
            hasError = true;
            exceptionDetails += ex;
        }

        if (hasError) {
            throw exceptionDetails;
        }
    }

    this.CheckUserInput = function () {
        var roleName = this.NameBox.get_value();
        var roleDescription = this.DescriptionBox.get_value();

        var regExp = new RegExp("^[a-zA-Z0-9_]{2,255}$");
        var regExp2 = new RegExp("^[a-zA-Z0-9_\"\$%&@\!/\n\\s,.:\(\)]{2,255}$");

        if (regExp.test(roleName)) {
            if (regExp2.test(roleDescription)) {
                return true;
            }
        }

        N_NotifyMessage('Invalid Data', 'Check if the role name or description has any of the follwing:<ul><li>Special Chanrectors (-#^*{}[]|-+=<>?\\)</li><li>Exceeds more than 255 charecors or less then 2 charectors.</li></ul>', 3);
        return false;
    }

    this.PerformSaveOperation = function () {
        var roleID = this.RoleID.value;
        var roleName = this.NameBox.get_value();
        var roleDescription = this.DescriptionBox.get_value();
        var isDisabled = this.DisableCheck.checked;
        var privilegeTree = this.PrivilegeTree;

        if (this.CheckUserInput()) {

            var roleObject = new Landscape.Role();
            if (roleID == '' || roleID == 'undefined') {
                roleObject.ID = '00000000-0000-0000-0000-000000000000';
            }
            else {
                roleObject.ID = roleID;
            }

            roleObject.Name = roleName;
            roleObject.Description = roleDescription;
            roleObject.IsDisabled = isDisabled;
            roleObject.CreatedBy = MASTER_GetCurrentUserCode();
            roleObject.UpdatedBy = MASTER_GetCurrentUserCode();

            var selectedNodes = privilegeTree.get_checkedNodes();

            if (selectedNodes != null && selectedNodes.length > 0) {
                roleObject.Privileges = new Array();

                for (idx = 0; idx < selectedNodes.length; idx++) {
                    if (selectedNodes[idx].get_attributes() != null &&
                        selectedNodes[idx].get_attributes().getAttribute('Type') != null &&
                        selectedNodes[idx].get_attributes().getAttribute('Type').indexOf('P') != -1) {
                        //If Selected node is a leaf
                        roleObject.Privileges.push(selectedNodes[idx].get_value());
                    }
                }
            }
            Landscape.AdministrativeActions.SaveRole(roleObject, function (result, e) { N_NotifyMessage('Success !!!', 'The role details save successfully.', 1); }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });
        }
    }

    this.PerformListOperation = function () {
        var hasError = false;
        var exceptionDetails = '';

        if (this.SearchGrid == null) {
            hasError = true;
            exceptionDetails += 'Cannot load search grid.';
        }

        var gridMasterTable = this.SearchGrid.get_masterTableView();
        if (!hasError) {
            Landscape.AdministrativeActions.GetRolesByPage(gridMasterTable.get_currentPageIndex(), gridMasterTable.get_pageSize(), function (result, e) {                
                e.set_dataSource(result);
                e.dataBind();
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, gridMasterTable);

            Landscape.AdministrativeActions.GetRolesCount(function (result, e) {                
                e.set_virtualItemCount(result);
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, gridMasterTable);

            this.SelectTabByName('Search Results');
        }
        else {
            throw exceptionDetails;
        }
    }

    this.PerformDeleteOperation = function () {
        if (confirm('Do you want to delete this role?')) {
            Landscape.AdministrativeActions.DeleteRole(this.RoleID.value, function (result, e) {
                N_NotifyMessage('Success !!!', 'Selected role was deleted.', 1);
                this.PerformNewOperation();
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });
        }
    }

    this.LoadRoleData = function (pRoleID) {
        this.PerformNewOperation();
        this.RoleID.value = pRoleID;
        Landscape.AdministrativeActions.GetRoleByID(pRoleID, function (reault, e) {
            e.NameBox.set_value(reault.Name);
            e.DescriptionBox.set_value(reault.Description);
            e.DisableCheck.checked = reault.IsDisabled;

            e.PrivilegeTree.trackChanges();
            for (idx = 0; idx < reault.Privileges.length; idx++) {
                var attVal = 'P_' + reault.Privileges[idx];
                var node = e.PrivilegeTree.findNodeByAttribute('Type', attVal);
                if (node != null)
                    node.check(true);
            }
            e.PrivilegeTree.commitChanges();
        }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, this);
    }

    this.CheckForDuplicateRoleName = function (pArguments) {
        if (!(this.RoleID.value != '' && pArguments.get_oldValue() == '')) {
            Landscape.AdministrativeActions.CheckDuplicateRole(this.NameBox.get_value(), function (result, e) {
                if (result) {
                    N_NotifyMessage('Duplicate Role', 'The entered role name already exists in the system. Please use a diffrent name.', 2);
                    e.set_value('');
                }
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, this.NameBox);
        }
    }

    this.LoadPrivileges = function () {
        Landscape.AdministrativeActions.GetAllInternalSystemModulesByParentID(null, onSMDataRecieved, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, this.PrivilegeTree);
    }

    function onSMDataRecieved(result, e) {        
        var treeView = e;
        if (treeView != null) {

            treeView.trackChanges();

            for (var i = 0; i < result.length; i++) {
                var node = new Telerik.Web.UI.RadTreeNode();
                var r = result[i];

                node.set_text(r.Name);
                node.set_value(r.ID);
                node.set_toolTip(r.Description);
                node.set_expandMode(Telerik.Web.UI.TreeNodeExpandMode.ClientSide);
                var attributes = node.get_attributes();
                attributes.setAttribute('Type', 'M_' + r.ID);
                treeView.get_nodes().add(node);

                if (r.IsLeaf) {
                    for (var idx = 0; idx < r.Privileges.length; idx++) {
                        var pNode = new Telerik.Web.UI.RadTreeNode();
                        pNode.set_text(r.Privileges[idx].Name);
                        pNode.set_value(r.Privileges[idx].ID);
                        pNode.set_toolTip(r.Privileges[idx].Description);
                        pNode.set_expandMode(Telerik.Web.UI.TreeNodeExpandMode.ClientSide);
                        var attributes = pNode.get_attributes();
                        attributes.setAttribute('Type', 'P_' + r.Privileges[idx].ID);

                        node.get_nodes().add(pNode);
                    }
                }
                else {
                    addChildNodes(node, r.ID, e);
                }
            }

            treeView.commitChanges();
        }
    }

    function addChildNodes(pParentNode, pParentValue, pTreeView) {
        
        Landscape.AdministrativeActions.GetAllInternalSystemModulesByParentID(pParentValue,
            function (result, e) {
                var treeView = pTreeView
                if (treeView != null) {

                    treeView.trackChanges();
                    
                    for (var i = 0; i < result.length; i++) {
                        var node = new Telerik.Web.UI.RadTreeNode();
                        var r = result[i];

                        node.set_text(r.Name);
                        node.set_value(r.ID);
                        node.set_toolTip(r.Description);
                        node.set_expandMode(Telerik.Web.UI.TreeNodeExpandMode.ClientSide);
                        var attributes = node.get_attributes();
                                                
                        if (r.IsLeaf) {
                            for (var idx = 0; idx < r.Privileges.length; idx++) {
                                var pNode = new Telerik.Web.UI.RadTreeNode();
                                pNode.set_text(r.Privileges[idx].Name);
                                pNode.set_value(r.Privileges[idx].ID);
                                pNode.set_toolTip(r.Privileges[idx].Description);
                                pNode.set_expandMode(Telerik.Web.UI.TreeNodeExpandMode.ClientSide);
                                var attributes = pNode.get_attributes();
                                attributes.setAttribute('Type', 'P_' + r.Privileges[idx].ID);

                                node.get_nodes().add(pNode);
                            }
                        }
                        else {
                            attributes.setAttribute('Type', 'M_' + r.ID);
                        }

                        pParentNode.get_nodes().add(node);

                        if (!r.IsLeaf)
                            addChildNodes(node, r.ModuleID);
                    }

                    treeView.commitChanges();
                }
            }
            , function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }
        );
    }
}